import sys
import os
import time

from socf import conf
from socf.client import local
from socf.client import service
from socf.services.constants import *

from WSDiscovery import *

def convertServiceListToMap(list):
    map = {}
    for entry in list:
        map[entry[0]] = entry[1].__str__()
    return map
    
class GPSService:
    
    def __init__(self):
        #creates configuration context
        configContext = conf.ConfigurationContext(os.path.join(os.getcwd(),  "conf"))
        #get service stub provider
        localProvider = local.LocalObjectStubProvider.createProvider(configContext, "dbus")
        #contact the discovery service
        discoveryStub = localProvider.getServiceClientStub(DISCOVERY_SERVICE_TYPE, "dbus:laf.socf/server/discoveryService")
        #print discoveryStub.getCurrentServicesList()[0]
        servicesMap = convertServiceListToMap(discoveryStub.getCurrentServicesList())
        if servicesMap.has_key(GPS_SERVICE_TYPE):
            self.__gps = localProvider.getServiceClientStub(GPS_SERVICE_TYPE, servicesMap[GPS_SERVICE_TYPE])
        else:
            self.__gps = None

    def get_info(self):
        """get GPS info
        

##wsdl:xsd:string
"""

        ret = ""
        if self.__gps == None:
            return ret
            
        # returns - (lat, lon, alt, speed, dir, time - (HH, MM, SS, MS), date(YY, MM, DD), status1, status2)
        info = self.__gps.getLocation()
        if info[7]:        
            #print "Lat: " + str(info[0]) + " degrees"
            ret += str(info[0]) + "#"
            #print "Lon: " + str(info[1]) + " degrees"
            ret += str(info[1]) + "#"
            if info[8]:
                #print "Alt: " + str(info[2]) + " m"
                ret += str(info[2]) + "#"
            else:
                #print "Alt: n/a"
                ret += str("n/a") + "#"
            #print "Speed: " + str(info[3]) + " ms-1"
            ret += str(info[3]) + "#"
            #print "Direction: " + str(info[4]) + " degrees"
            ret += str(info[4]) + "#"
            #print "Time: " + str(info[5][0]) + ":" + str(info[5][1]) + ":" + str(info[5][2]) + " UTC"
            ret += str(info[5][0]) + ":" + str(info[5][1]) + ":" + str(info[5][2]) + "#"
            #print "Date: " + str(info[6][0]) + "/" + str(info[6][1]) + "/" + str(info[5][2])
            ret += str(info[6][0]) + "/" + str(info[6][1]) + "/" + str(info[5][2]) + "#"
            
        return ret

if __name__=="__main__":
    try:
        gps = GPSService()
        print gps.get_info()
        ss = service.ServiceContainer("192.168.2.253", 8000)
        serviceUrl = ss.addServiceObject(gps,  "gps_service")
        ss.start()
        wsd = WSDiscovery()
        wsd.start()
        type = QName("gps", "gps")
        wsd.publishService(types=[type], scopes=[], xAddrs=[serviceUrl])
        while True:
            time.sleep(0.5)
    except KeyboardInterrupt:
        print "\nShutdown.."
        wsd.stop()
        ss.stop()

